package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.market;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.CloudPayAccountAPIService;
import com.gzhryc.net_marketing.api.protocol.account.CloudPayAccountSearchOrderInfoResponse;
import com.gzhryc.net_marketing.core.enums.EGoodsClassify;
import com.gzhryc.net_marketing.core.enums.EReceiveGoodsType;
import com.gzhryc.net_marketing.core.enums.GoodsOrderEnum;
import com.gzhryc.net_marketing.supplier.Supplier;
import com.gzhryc.net_marketing.supplier.SupplierManager;
import com.gzhryc.net_marketing.supplier.pay.dao.db.SupplierBusinessOrder;
import com.gzhryc.net_marketing.supplier.pay.dao.db.SupplierBusinessOrderLog;
import com.gzhryc.net_marketing.supplier.pay.services.SupplierBusinessOrderLogService;
import com.gzhryc.net_marketing.supplier.pay.services.SupplierBusinessOrderService;
import com.gzhryc.net_marketing.supplier.pay.services.dto.SupplierBusinessOrderSearch;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

public class SupplierBusinessOrderController {

	static Logger log = Logger.getLogger(SupplierBusinessOrderController.class);

	@Route(value = { "/market/order/list.html" })
	public String list(HttpServletRequest request) {
		request.setAttribute("stateList", GoodsOrderEnum.State.values());
		request.setAttribute("supplyStateList", GoodsOrderEnum.SupplyState.values());
		return "/market/order/list.html";
	}

	@Route(value = "/market/order/list.data")
	public ListResult<SupplierBusinessOrder> listData(HttpServletRequest request) {
		ListResult<SupplierBusinessOrder> result = new ListResult<SupplierBusinessOrder>(DtoConstants.NULL_DATA, "暂无数据");
		Supplier supplier = SupplierManager.getSupplier();
		if(supplier != null) {
			SupplierBusinessOrderSearch search = WebUtils.getParameter(request, SupplierBusinessOrderSearch.class);
			Integer pageNo = WebUtils.getInteger(request, "page", 1);
			Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
	
			result.getBody().setTotal(SupplierBusinessOrderService.self(supplier.getJdbcKey()).countBySearch(search));
			result.getBody().setData(SupplierBusinessOrderService.self(supplier.getJdbcKey()).findBySearch(search, pageNo, pageLimit));
	
			if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
				result.setCode(DtoConstants.SUCCESS, null);
			}
		}
		return result;
	}

	@Route(value = { "/market/order/info.html" })
	public String info(HttpServletRequest request) {
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request,"tradeNo");
		SupplierBusinessOrder businessOrder = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(tradeNo);
		if(businessOrder != null) {
			WebUtils.setAttribute(request, businessOrder);
			if(supplier.getAccountId() != null && StringTools.isNotBlank(supplier.getVisitToken())) {
				CloudPayAccountSearchOrderInfoResponse orderInfoResponse = CloudPayAccountAPIService.self().searchOrder(supplier.getAccountId()
						,supplier.getVisitToken(),businessOrder.getTradeNo());
				if(orderInfoResponse != null && DefaultAPICodeConstants.SUCCESS.equals(orderInfoResponse.getCode())){
					request.setAttribute("payOrder",orderInfoResponse.getBody());
				}
			}
		}
		return "/market/order/info.html";
	}

	@Route(value = { "/market/order/goods/state/search.do" })
	public AjaxResult doSearch(HttpServletRequest request, HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "查询订单支付状态失败");
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request,"tradeNo");
		if(StringTools.isNotBlank(tradeNo) && supplier != null) {
			SupplierBusinessOrder order = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(tradeNo);
			if (order == null) {
				result.setMsg("未找到订单信息");
				return result;
			}

			try {
				if(SupplierBusinessOrderService.self(supplier.getJdbcKey()).searchOrderInfo(supplier,order)) {
					result.setCode(DtoConstants.SUCCESS,null);
				}
			} catch (LogicException e) {
				result.setBody(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = { "/market/order/goods/confirm.do" })
	public AjaxResult doConfirm(HttpServletRequest request, HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "确定订单操作失败");
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request,"tradeNo");
		if(StringTools.isNotBlank(tradeNo) && supplier != null) {
			SupplierBusinessOrder order = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(tradeNo);
			if (order == null) {
				result.setMsg("未找到订单信息");
				return result;
			}
			
			User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);

			OperateInfo operateInfo = new OperateInfo();
			operateInfo.setProgramType(WebConstants.PROGRAM_TYPE);
			operateInfo.setOperatorType(EOperatorType.Agent.index());
			operateInfo.setOperator(loginUser.getFullName());

			try {
				if(SupplierBusinessOrderService.self(supplier.getJdbcKey()).confirmOrder(order,GoodsOrderEnum.SupplyState.FinishConfirm.index()
						,operateInfo)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setBody(e.getMessage());
			}

		}
		return result;
	}

	/**
	 * 发货
	 * @param request
	 * @return
	 */
	@Route(value = { "/market/order/goods/deliver.html" })
	public String deliverGoods(HttpServletRequest request) {
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request,"tradeNo");
		SupplierBusinessOrder order = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(tradeNo);
		if(order != null){
			WebUtils.setAttribute(request,order);
			if(EGoodsClassify.Fictitious.index().equals(order.getGoodsClassify())) {
				return "/market/order/fictitious.html";
			}
		}
		return "/market/order/logistics.html";
	}

	/**
	 * 发货处理
	 * @param request
	 * @return
	 */
	@Route(value = { "/market/order/goods/deliver.do" })
	public AjaxResult doDeliverGoods(HttpServletRequest request, HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"发货操作失败");
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request,"tradeNo");
		Date deliverGoodsDate = WebUtils.getDate(request,"deliverGoodsDate");
		if(StringTools.isNotBlank(tradeNo) && deliverGoodsDate != null && supplier != null) {
			SupplierBusinessOrder order = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(tradeNo);
			if(order == null){
				result.setMsg("未找到订单信息");
				return result;
			}
			
			User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);

			OperateInfo operateInfo = new OperateInfo();
			operateInfo.setProgramType(WebConstants.PROGRAM_TYPE);
			operateInfo.setOperatorType(EOperatorType.Agent.index());
			operateInfo.setOperator(loginUser.getFullName());

			if(EGoodsClassify.Fictitious.index().equals(order.getGoodsClassify())){
				String deliverGoodsNote = WebUtils.getString(request,"deliverGoodsNote");
				try {
					if(SupplierBusinessOrderService.self(supplier.getJdbcKey()).deliveryGoods(order,deliverGoodsNote,deliverGoodsDate
							,operateInfo)) {
						result.setCode(DtoConstants.SUCCESS, null);
					}
				} catch (LogicException e) {
					result.setBody(e.getMessage());
				}
			}else{
				String logisticsCompanyId = WebUtils.getString(request,"logisticsCompanyId");
				String logisticsTradeNo = WebUtils.getString(request,"logisticsTradeNo");
				try {
					if(SupplierBusinessOrderService.self(supplier.getJdbcKey()).logisticsDeliveryGoods(order,logisticsCompanyId
							,logisticsTradeNo,deliverGoodsDate,operateInfo)) {
						result.setCode(DtoConstants.SUCCESS, null);
					}
				} catch (LogicException e) {
					result.setBody(e.getMessage());
				}
			}
		}
		return result;
	}

	@Route(value = { "/market/order/goods/receive.html" })
	public String receiveGoods(HttpServletRequest request) {
		return "/market/order/receive.html";
	}

	@Route(value = { "/market/order/goods/receive.do" })
	public AjaxResult doReceiveGoods(HttpServletRequest request, HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "确认收货失败");
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request, "tradeNo");
		Date receiveGoodsDate = WebUtils.getDate(request, "receiveGoodsDate");
		if (StringTools.isNotBlank(tradeNo) && receiveGoodsDate != null) {
			User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
			  
			OperateInfo operateInfo = new OperateInfo();
			operateInfo.setProgramType(WebConstants.PROGRAM_TYPE);
			operateInfo.setOperatorType(EOperatorType.Agent.index());
			operateInfo.setOperator(loginUser.getFullName());

			try {
				if(SupplierBusinessOrderService.self(supplier.getJdbcKey()).receiveGoods(tradeNo,EReceiveGoodsType.ManagerConfirm.index()
						,receiveGoodsDate,operateInfo)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = { "/market/order/goods/evaluate.html" })
	public String evaluateGoods(HttpServletRequest request) {
		return "/market/order/evaluate.html";
	}

	@Route(value = { "/market/order/goods/evaluate.do" })
	public AjaxResult doEvaluateGoods(HttpServletRequest request, HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "评价失败");
		String tradeNo = WebUtils.getString(request, "tradeNo");
		if (StringTools.isNotBlank(tradeNo)) {
			Supplier supplier = SupplierManager.getSupplier();
			try {
				SupplierBusinessOrder businessOrder = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(tradeNo);
				if(businessOrder == null){
					throw new LogicException("未找到业务订单");
				}

				if(!GoodsOrderEnum.State.WaitEvaluate.index().equals(businessOrder.getState())){
					throw new LogicException("业务订单未收货");
				}else{
					Integer times = DateTools.differenceDay(businessOrder.getReceiveGoodsDate(),new Date());
					if(times < 7){
						throw new LogicException("业务订单收货未到7天");
					}
				}

				OperateInfo operateInfo = new OperateInfo();
				operateInfo.setProgramType(WebConstants.PROGRAM_TYPE);
				operateInfo.setOperator(supplier.getName());
				operateInfo.setOperatorType(EOperatorType.Manager.index());
				operateInfo.setOperateNote("默认评价");

				if (SupplierBusinessOrderService.self(supplier.getJdbcKey()).evaluateGoods(supplier,businessOrder,operateInfo)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = "/market/order/logs/list.data")
	public ListResult<SupplierBusinessOrderLog> logsListData(HttpServletRequest request) {
		ListResult<SupplierBusinessOrderLog> result = new ListResult<SupplierBusinessOrderLog>(DtoConstants.NULL_DATA,"暂无数据");
		Supplier supplier = SupplierManager.getSupplier();
		String tradeNo = WebUtils.getString(request,"tradeNo");
		result.getBody().setData(SupplierBusinessOrderLogService.self(supplier.getJdbcKey()).findByTradeNo(tradeNo));
		if(result.getBody().getData() != null && result.getBody().getData().size() > 0){
			result.setCode(DtoConstants.SUCCESS,null);
		}
		return result;
	}
}
